package io.hellsinger.vortex.data

import android.os.Parcelable
import kotlinx.parcelize.Parcelize

interface Line :
    CharSequence,
    Parcelable {
    override val length: Int

    fun toCharArray(): CharArray

    override fun subSequence(
        startIndex: Int,
        endIndex: Int,
    ): Line
}

// Memory optimization
@Parcelize
object EmptyLine : Line {
    override val length: Int
        get() = 0

    override fun toCharArray(): CharArray = CharArray(0)

    override fun get(index: Int): Char = Char(0)

    override fun subSequence(
        startIndex: Int,
        endIndex: Int,
    ): Line = this
}

@Parcelize
private class DefaultLineImpl(
    val content: CharSequence,
) : Line {
    override val length: Int = content.length

    override fun toCharArray(): CharArray = CharArray(content.length, content::get)

    override fun subSequence(
        startIndex: Int,
        endIndex: Int,
    ): Line = DefaultLineImpl(content = content.subSequence(startIndex, endIndex))

    override operator fun get(index: Int): Char = content[index]
}

fun Line(content: CharSequence): Line = DefaultLineImpl(content)
